package com.xiaoyu.client.ui.activity.nearby;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.techfansy.moreImageSelected.ImagePicker;
import com.techfansy.moreImageSelected.MoreImageMethod;
import com.techfansy.moreImageSelected.bean.ImageItem;
import com.techfansy.provinceCitySelect.ProvinceCitySelect;
import com.xiaoyu.client.R;
import com.xiaoyu.client.loader.banner.StoreImageLoader;
import com.xiaoyu.client.model.StoreCreBanModel;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.commonlib.BillionCardConstants;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.base.BaseActivityWithTitle;
import com.xiaoyu.commonlib.utils.CheckFormatUtils;
import com.xiaoyu.commonlib.utils.ToastUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 推荐入住页面
 * Created by jk 2018/11/15
 */
public class ShopRecomAddActivity extends BaseActivityWithTitle {
    @BindView(R.id.activity_shop_recom_add_banner)
    Banner mBanner;//轮播图
    @BindView(R.id.activity_shop_recom_add_take_photo)
    RelativeLayout mTakeLayout;//拍照提示图
    @BindView(R.id.activity_shop_add_recom_name_edit)
    EditText mStoreNameEdit;//商铺名称
    @BindView(R.id.activity_shop_add_recom_tag_txt)
    TextView mStoreTagTxt;//商铺类型
    @BindView(R.id.activity_shop_add_recom_location_txt)
    TextView mStoreCityTxt;//商铺城市
    @BindView(R.id.activity_shop_add_recom_address_edit)
    EditText mAddressEdit;//详细地址
    @BindView(R.id.activity_shop_add_recom_owner_name_edit)
    EditText mOwnerNameEdit;//店主姓名
    @BindView(R.id.activity_shop_add_recom_owner_phone1_edit)
    EditText mOwnerPhone1Edit;//店主电话
    @BindView(R.id.activity_shop_add_recom_owner_phone2_edit)
    EditText mOwnerPhone2Edit;//备用电话
    private ImageView mRightImg;//

    private Context mContext;
    private MoreImageMethod moreImageMethod;
    private ImagePicker imagePicker;
    private List<ImageItem> mList = new ArrayList<>();//选中的图片list

    public static final String SHOP_TAG_LIST = "shop_tag_list";
    private Map<String, String> mTagList = new HashMap<>();//选择的商铺类型列表数据
    private final int TYPE_CODE = 1;//类型
    private List<StoreCreBanModel> bannerImgs = new ArrayList<>();//轮播图数据列表


    @Override
    protected void loadContentView(ViewGroup parent) {
        setTitleText("附近商家");
        mContext = this;
        LayoutInflater.from(this).inflate(R.layout.activity_shop_recom_add, parent, true);
        ButterKnife.bind(this);
        addRightImg();
        initBanner();
        moreImageMethod = new MoreImageMethod();
        imagePicker = ImagePicker.getInstance();
        imagePicker.clear();
    }


    //顶部导航栏右方按钮
    private void addRightImg() {
        mRightImg = new ImageView(this);
        mRightImg.setImageResource(R.mipmap.icon_share);
        mRightImg.setOnClickListener(this);
        addRightView(mRightImg, 0);
        mRightImg.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == mRightImg) {//分享
            ToastUtil.showBelowToast(this, "分享点击");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == TYPE_CODE && 0 == resultCode && data != null) {//商铺类型
            mTagList = (Map<String, String>) data.getExtras().getSerializable(SHOP_TAG_LIST);
            StringBuilder builder = new StringBuilder();
            Iterator iterator = mTagList.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry) iterator.next();
                builder.append(entry.getValue().toString() + ",");
            }
            mStoreTagTxt.setText(builder.toString().substring(0, builder.toString().length() - 1));
            mStoreTagTxt.setTextColor(Color.parseColor("#333333"));
        } else {
            //接收回调的图片
            moreImageMethod.onActivityResult(requestCode, resultCode, data, imagePicker, mList, ShopRecomAddActivity.this);
            bannerImgs.clear();
            for (int i = 0; i < mList.size(); i++) {
                bannerImgs.add(i, new StoreCreBanModel(mList.get(i).getPaths(), 0));
            }
            if (mList.size() < 3) {
                bannerImgs.add(mList.size(), new StoreCreBanModel(R.mipmap.paizhao, 1));
            }
            mBanner.setImages(bannerImgs);
            mBanner.start();
            mTakeLayout.setVisibility(View.GONE);
            mBanner.setVisibility(View.VISIBLE);
        }

    }

    //上传图片值OSS
    private void uploadImg() {
        for (int i = 0; i < mList.size(); i++) {
            uploadOSSUrl(mList.get(i).getPaths(), mList.get(i).getName(), i);
        }
    }

    private void uploadOSSUrl(String filePath, String objectKey, int position) {
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(BillionCardConstants.BACKET_NAME, objectKey, filePath);
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(BillionCardConstants.ACCESS_KEY_ID, BillionCardConstants.ACCESS_KEY_SECRET);
        try {
            OSSClient oss = new OSSClient(this, BillionCardConstants.ENDPOINT, credentialProvider);
            PutObjectResult putResult = oss.putObject(put);
            if (position != mList.size() - 1) return;
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < mList.size(); i++) {
                builder.append("https://yikabangb.oss-cn-beijing.aliyuncs.com/" + mList.get(i).getName());
                builder.append(i != mList.size() - 1 ? "," : "");
            }

            sendStoreAdd((builder.toString()));//调取接口上传内容

        } catch (ClientException e) {
            // 本地异常如网络异常等
            e.printStackTrace();
        } catch (ServiceException e) {
            // 服务异常
        }
    }

    //初始化轮播图
    private void initBanner() {
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        mBanner.setIndicatorGravity(BannerConfig.CENTER);
        //设置是否自动轮播（不设置则默认自动）
        mBanner.isAutoPlay(true);
        //设置是否允许手动滑动轮播图
        mBanner.setViewPagerIsScroll(true);
        //设置轮播图片间隔时间（不设置默认为2000）
        mBanner.setDelayTime(2000);
        mBanner.setImageLoader(new StoreImageLoader());
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if (bannerImgs.get(position).getType() == 1) {
                    moreImageMethod.setClick(ShopRecomAddActivity.this, mList, imagePicker);
                }
            }
        });
    }

    //拍摄图片提示图
    @OnClick(R.id.activity_shop_recom_add_take_photo)
    public void takePhotoClick() {
        moreImageMethod.setClick(this, mList, imagePicker);
    }


    //商铺类型
    @OnClick(R.id.store_type_item)
    public void storeTypeClick() {
        Intent intent = new Intent(this, ShopTypeActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(SHOP_TAG_LIST, (Serializable) mTagList);
        intent.putExtras(bundle);
        startActivityForResult(intent, TYPE_CODE);
    }


    //商铺城市
    @OnClick(R.id.store_place_item)
    public void storeCityClick() {
        new ProvinceCitySelect().createBottom(this).setSureListener(new ProvinceCitySelect.OnClickListener() {
            @Override
            public void sure(String strProvince, String strCity, String strDistrict) {
                mStoreCityTxt.setText(strProvince + strCity + strDistrict);
                mStoreCityTxt.setTextColor(Color.parseColor("#333333"));
            }
        }).show();
    }

    //提交按钮
    @OnClick(R.id.activity_shop_add_recom_commit_btn)
    public void commitClick() {
        uploadImg();
    }

    /**
     * 添加推荐商铺
     */
    private void sendStoreAdd(String seekimg) {
        String tagId = "";//商铺标签所有id的字符串
        if (mTagList.size() != 0) {
            StringBuilder builder = new StringBuilder();
            Iterator iterator = mTagList.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry) iterator.next();
                builder.append(entry.getKey().toString() + ",");
            }
            tagId = builder.toString().substring(0, builder.toString().length() - 1);
        }
        String name = mStoreNameEdit.getText().toString();//商铺名称
        String city = mStoreCityTxt.getText().toString();//商铺所在城市
        String address = mAddressEdit.getText().toString();//商铺详细地址
        String ownerName = mOwnerNameEdit.getText().toString();//店主姓名
        String phone1 = mOwnerPhone1Edit.getText().toString();//店主电话
        String phone2 = mOwnerPhone2Edit.getText().toString();//备用电话

        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(tagId) || TextUtils.isEmpty(city) || TextUtils.isEmpty(address)
                || TextUtils.isEmpty(ownerName) || TextUtils.isEmpty(phone1) || TextUtils.isEmpty(phone2) || mList.size() == 0) {
            ToastUtil.showToast(this, getResources().getString(R.string.please_input_info));
            return;
        }

        if (CheckFormatUtils.checkMobilePhone(mOwnerPhone1Edit.getText().toString()) == 2 ||
                CheckFormatUtils.checkMobilePhone(mOwnerPhone2Edit.getText().toString()) == 2) {
            ToastUtil.showToast(this, "手机号不合法");
            return;
        }
        showLoading();
        NetworkManager.sendAddRecommendShop(name, seekimg, tagId, address, city, ownerName, phone1, phone2, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                dissmissLoading();
                ToastUtil.showToast(mContext, "提交成功！");
                finish();
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {

            }
        });
    }


}
